﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using WebApiV2.Data;
using WEBapp001.Domain;
using WEBapp001.Interface;

namespace WEBapp001.Implementation
{
    public class EfRespository<T> : IRespository<T> where T:BaseEntity
    {
        private readonly DbSchoolContext db;
        private DbSet<T> _Entity;

        protected DbSet<T> Entity
        {
            get
            {
                if (_Entity == null)
                {
                    _Entity = db.Set<T>();
                }
                return _Entity;
            }
            
        }
        public IQueryable<T> Table
        {
            get
            {
                return Entity;
            }
        }
        public EfRespository(DbSchoolContext schoolContext)
        {
            db = schoolContext;
        }

        public void BulkInsert(IEnumerable<T> list)
        {
            Entity.AddRange(list);

            db.SaveChanges();
        }

        public void Delete(T entity)
        {
            this.Entity.Remove(entity);
            db.SaveChanges();
        }

        public void Delete(int id)
        {
            var row = Table.Where(x=>x.Id==id).FirstOrDefault();
            Delete(row);
            db.SaveChanges();
        }

        
        public T GitById(int id)
        {
            //T t = null;
            
            return Entity.Where(x => x.Id == id).FirstOrDefault();
            
        }

        public void Insert(T entity)
        {
            Entity.Add(entity);
            db.SaveChanges();
        }

        public void Update(T entity)
        {
            Entity.Update(entity);
            db.SaveChanges();
        }

      
        

     
    }
}
